package com.health.trans.processor.reader;

import com.health.trans.annotation.Reader;
import com.health.trans.kit.ReaderConfig;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.database.JdbcPagingItemReader;
import org.springframework.batch.item.database.builder.JdbcPagingItemReaderBuilder;
import org.springframework.batch.item.database.support.MySqlPagingQueryProvider;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

/**
 * @author nqlz
 */
@Reader
public class JdbcPageReader implements CsReader {

    /**
     * 让读者
     * 获取页面阅读器
     * 分页
     *
     * @param readerConfig 读者配置
     * @return {@link ItemReader}<{@link T}>
     */
    @Override
    public <T> ItemReader<T> getReader(ReaderConfig<T> readerConfig) {
        MySqlPagingQueryProvider provider = new MySqlPagingQueryProvider();
        provider.setSortKeys(readerConfig.getSortKeys());
        provider.setSelectClause(readerConfig.getSql());
        JdbcPagingItemReader<T> build = new JdbcPagingItemReaderBuilder<T>()
                .name(readerConfig.getTableClass().getSimpleName() + "ItemReader")
                .dataSource(readerConfig.getDataSource())
                .pageSize(readerConfig.getPageSize())
                .rowMapper(new BeanPropertyRowMapper<>(readerConfig.getTableClass()))
                .queryProvider(provider)
                .build();

        try {
            build.afterPropertiesSet();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (readerConfig.getMaxCount() > 0) {
            build.setMaxItemCount(readerConfig.getMaxCount());
        }
        return build;
    }
}
